# coding: utf-8
import os
import sys
from pathlib import Path
from typing import Union, Callable, Any

import chardet
from PIL import Image
from PySide6.QtCore import QUrl, QProcess
from PySide6.QtGui import QDesktopServices


def isWin11():
    return sys.platform == 'win32' and sys.getwindowsversion().build >= 22000


def openUrl(url: Union[str, Path]):
    if isinstance(url, Path):
        url = url.as_posix()
    if not url.startswith("http"):
        if not os.path.exists(url):
            return False
        QDesktopServices.openUrl(QUrl.fromLocalFile(url))
    else:
        QDesktopServices.openUrl(QUrl(url))

    return True


def get_folder_size(folder: Union[Path, str]):
    if isinstance(folder, str):
        folder = Path(folder)
    size = 0
    for item in folder.glob('**/*'):
        if not item.is_file():
            continue
        size += item.stat().st_size
    return size


def image_convert(input_path: str, output_path: str, fmt='PNG'):
    """
    图片格式转换
    :param input_path: 输入PNG图片路径
    :param output_path: 输出ICO图片路径
    :param fmt: 输入图片格式，默认为PNG
    :return:
    """
    with Image.open(input_path) as img:
        if img.mode != 'RGBA':
            img = img.convert('RGBA')
        img.save(output_path, format=fmt)


def decoding_bytes(data: bytes) -> str:
    """
    解码字节数据
    :param data: 字节数据
    :return: 解码后的字节数据
    """
    encoding = chardet.detect(data)['encoding']
    if encoding is None:
        return data.decode('utf-8', 'ignore')
    return data.decode(encoding, 'ignore')


def runProcess(executable: Union[str, Path], args=None, timeout=5000, cwd=None) -> str:
    process = QProcess()

    if cwd:
        process.setWorkingDirectory(str(cwd))

    process.start(str(executable).replace("\\", "/"), args or [])
    process.waitForFinished(timeout)
    return process.readAllStandardOutput().toStdString().strip()


def worker_result(slot: Callable, result: Any):
    if slot:
        slot(result)
